public static System.Data.DataTable ToDataTable<T>(this IList<T> data)
{
System.ComponentModel.PropertyDescriptorCollection properties =
System.ComponentModel.TypeDescriptor.GetProperties(typeof(T));
System.Data.DataTable table = new System.Data.DataTable();
foreach (System.ComponentModel.PropertyDescriptor prop in properties)
{
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
}
foreach (T item in data)
{
System.Data.DataRow row = table.NewRow();
foreach (System.ComponentModel.PropertyDescriptor prop in properties)
{
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
}
table.Rows.Add(row);
}
return table;
}
{
System.ComponentModel.PropertyDescriptorCollection properties =
System.ComponentModel.TypeDescriptor.GetProperties(typeof(T));
System.Data.DataTable table = new System.Data.DataTable();
foreach (System.ComponentModel.PropertyDescriptor prop in properties)
{
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
}
foreach (T item in data)
{
System.Data.DataRow row = table.NewRow();
foreach (System.ComponentModel.PropertyDescriptor prop in properties)
{
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
}
table.Rows.Add(row);
}
return table;
}